<?php

namespace app\common\model;

use think\Model;
use think\Db;

class UserAgent extends Model
{
    public function user() 
    {
        return $this->belongsTo('User', 'uid', 'uid')->field('uid,name,tel');
    }

    public function agent()
    {
        return $this->belongsTo('User', 'agent_uid', 'uid')->field('uid,name,tel');
    }

    // public function getStatusAttr($value, $data)
    // {
    //     $status = [-1=>'取消',0=>'待处理',1=>'待玩家确认',2=>'交易完成'];
    //     return $status[$data['status']];
    // }

    /**
     * 获取玩家代理交易列表
     *
     * @param [type] $map
     * @param [type] $size
     * @param string $field
     * @return void
     */
    public function getList($map, $size = null, $field = '*')
    {
        $list = $this->with('agent,user')
            ->where($map)->field($field)->order('create_time DESC')->paginate($size);

        return $list;
    }

    /**
     * 添加会员转账记录
     *
     * @param [type] $data
     * @return void
     */
    public function addInfo($data)
    {
        if ($data['num'] < config('trans_base') || $data['num'] % config('trans_base') > 0) {
            return msg_code('转账金额需为'.config('trans_base').'整数倍');
        }

        $us = db('user')->where('uid', $data['uid'])->field('s_pwd,kr_coin,province,city')->find();
        if ($us['kr_coin'] < $data['num']) {
            return msg_code('超出账户余额');
        }
        if ($us['s_pwd'] != encrypt($data['s_pwd'])) {
            return msg_code('支付密码不正确');
        }

        $agent_uid = db('user')->where('tel', $data['agent_id'])->value('uid');
        $agent = db('agent')->where('uid', $agent_uid)->find();

        if ($agent_uid && $agent) {
            // 判断代理区域
            // if (! config('cross_district')) {
            //     if ($us['province'] != $agent['province'] || $us['city'] != $agent['city']) {
            //         return msg_code('此代理与玩家不属于同一区域');
            //     }
            // }
            $addData = [
                'type' => $data['type'],
                'agent_id' => $agent['id'],
                'agent_uid' => $agent_uid,
                'uid' => $data['uid'],
                'trade_num' => $data['num'],
                'fee' => $data['num'] * config('trans_fee') / 100,
                'status' => 0
            ];

            Db::startTrans();
            try {
                model('User')->updateUserAcc($data['uid'], -$data['num'], 'kr_coin', '转账代理');
                $rst = $this->save($addData);
                Db::commit();
                return msg_code('操作成功', $rst);
            } catch (Exception $e) {
                Db::rollback();
                return msg_code($e->getMessage());
            }
        }
        
       return msg_code('代理不存在');
    }
    
    /**
     * 代理充值玩家
     *
     * @param [type] $uid
     * @param [type] $agent_uid
     * @param [type] $num
     * @return void
     */
    public function payCoin($uid, $agent_uid, $num, $note)
    {
        $data = [
            'type' => 2,
            'uid' => $uid,
            'agent_uid' => $agent_uid,
            'trade_num' => $num,
            'fee' => 0,
        ];
        Db::startTrans();
        try {
            $this->save($data);
            model('User')->updateUserAcc($agent_uid, -$num, 'kr_coin', '玩家充值扣除！');
            model('User')->updateUserAcc($uid, $num, 'kr_coin', '代理'.$note.'转账');
            // 添加充值记录
            model('AgentPayLog')->addInfo([
                'agent_uid' => $agent_uid,
                'uid' => $uid,
                'pay_num' => $num,
            ]);
            Db::commit();
            return msg_code('操作成功', 1);
        } catch (Exception $e) {
            Db::rollback();
            return msg_code($e->getMessage());
        }
    }

    /**
     * 由系统确认收款
     * 
     * @param  [type] $id   [description]
     * @param  string $note [description]
     * @return [type]       [description]
     */
    public function confirm($id, $note = '系统')
    {
        $info = $this->with('user')->where('id', $id)->field('type,agent_uid,uid,trade_num,status')->find();

        if ($info) {
            if ($info->status == 1) {
                Db::startTrans();
                try {
                    $this->where('id', $id)->update(['status' => 2, 'note' => $note.'确认收款']);
                    model('User')->updateUserAcc(
                        $info->agent_uid, 
                        $info->trade_num, 
                        'kr_coin', 
                        '玩家:'.$info->user->name.'转账#由'.$note.'确认收款'
                    );
                    Db::commit();
                    return msg_code('操作成功！', 1);
                } catch (Exception $e) {
                    return msg_code($e->getMessage());
                }
            }

            return msg_code('此交易状态异常');
        }   

        return msg_code('不存在此交易记录');
    }

    /**
     * 驳回玩家向代理的转账申请
     * 
     * @param  [type] $id   [description]
     * @param  string $note [description]
     * @return [type]       [description]
     */
    public function reject($id, $note = '')
    {
       $info = $this->with('agent')->where('id', $id)->find();

        if ($info) {
            if ($info->status == 0) {
                Db::startTrans();
                try {
                    $this->where('id', $id)->update(['status' => -1, 'note' => $note.'驳回转账请求']);
                    model('User')->updateUserAcc(
                        $info->uid, 
                        $info->trade_num, 
                        'kr_coin', 
                        $note.'驳回向代理：'.$info->agent->name.'/'.$info->agent->tel.'转账请求'
                    );
                    Db::commit();
                    return msg_code('操作成功！', 1);
                } catch (Exception $e) {
                    return msg_code($e->getMessage());
                }
            }

            return msg_code('此交易状态异常');
        }   

        return msg_code('不存在此交易记录'); 
    }

}
